const fs = require("fs");
const fse = require("fs-extra");
// const gm = require("gm");
// const potrace = require("potrace");
// const excelPort = require("excel-export");
var xlsx = require("node-xlsx");
const iconvLite = require("iconv-lite");
const qr = require("qr-image");
const dot = 11.811;

CanvasRenderingContext2D.prototype.roundRect = (x, y, w, h, r) => {
    if (w < 2 * r) r = w / 2;
    if (h < 2 * r) r = h / 2;
    this.beginPath();
    this.moveTo(x + r, y);
    this.arcTo(x + w, y, x + w, y + h, r);
    this.arcTo(x + w, y + h, x, y + h, r);
    this.arcTo(x, y + h, x, y, r);
    this.arcTo(x, y, x + w, y, r);
    this.closePath();
    return this;
};

const Uint8ToBase64 = function (u8Arr) {
    var CHUNK_SIZE = 0x8000; //arbitrary number
    var index = 0;
    var length = u8Arr.length;
    var result = "";
    var slice;
    while (index < length) {
        slice = u8Arr.subarray(index, Math.min(index + CHUNK_SIZE, length));
        result += String.fromCharCode.apply(null, slice);
        index += CHUNK_SIZE;
    }
    return btoa(result);
};

// 生成excel
const generateExcel = (datas, path) => {
    var title = ["name"];
    var excelData = [];
    excelData.push(title);
    datas.forEach((item) => {
        excelData.push([item.name]);
    });
    var buffer = xlsx.build([{ name: "sheet1", data: excelData }]);
    fs.writeFileSync(path, buffer);
    return;

    /**
     * 定义一个空对象，来存放表头和内容
     * cols，rows为固定字段，不可修改
     */
    const excelConf = {
        cols: [], // 表头
        rows: [], // 内容
    };
    // 表头
    for (let key in datas[0]) {
        excelConf.cols.push({
            caption: key,
            type: "string", // 数据类型
            width: 100, // 宽度
        });
    }
    // 内容
    datas.forEach((item) => {
        // 解构
        const { name, size, price } = item;
        excelConf.rows.push([name, size, price]);
    });
    // 调用excelPort的方法，生成最终的数据
    const result = excelPort.execute(excelConf);
    // 写文件
    fs.writeFileSync(path, result, "binary");
};

const getLen = (str, size) => {
    var length = 0;
    var texts = [];
    if (str.length != 1) {
        texts = str.split("");
    } else {
        texts[0] = str;
    }
    //非IE浏览器
    for (var i = 0; i < texts.length; i++) {
        if (isChinese(texts[i]) || isBig(texts[i])) {
            length += size;
        } else if (isWordOrNum(texts[i]) || isSmall(texts[i])) {
            length += size / 2;
        } else {
            window.measureCanvas.font = size + "px 黑体";
            length += window.measureCanvas.measureText(texts[i]).width;
        }
    }
    return length;
};

const isChinese = (temp) => {
    var re = /^[\u4E00-\u9FA5]/;
    if (re.test(temp)) return true;
    return false;
};

const isWordOrNum = (temp) => {
    var re = /^[A-Za-z0-9]/;
    if (re.test(temp)) return true;
    return false;
};

const isSmall = (temp) => {
    var re = new RegExp("[`~!@#$^&*()=|{}':;,\\[\\].<>/?]");
    if (re.test(temp)) return true;
    return false;
};

const isBig = (temp) => {
    var re = new RegExp("[《》！（）【】；：。，、？￥……‘’”“——]");
    if (re.test(temp)) return true;
    return false;
};

export default {
    fs,
    fse,
    // gm,
    // potrace,
    iconvLite,
    qr,
    dot,
    generateExcel,
    getLen,
    Uint8ToBase64,
};
